package com.common.easyui;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.model.Global;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 生成easyui的各种josn，主要是普通树状和treegrid
 * 
 * @author chenjun
 *
 */
public class EasyuiUtils {

	public static void addFilter(Map<String, Object> queryMap) {
		if (queryMap.get("filterRules") != null) {
			JSONArray jsonArray = JSONArray.parseArray(queryMap.get("filterRules").toString());
			for (Object object : jsonArray) {
				JSONObject jsonObject = (JSONObject) object;
				if (jsonObject.get("value").toString().equals("是")) {
					jsonObject.put("value", Global.YES + "");
				} else if (jsonObject.get("value").toString().equals("否")) {
					jsonObject.put("value", Global.NO + "");
				}
			}
			queryMap.put("filter", jsonArray);
		}
	}

	/**
	 * 添加pagenum属性
	 * 
	 * @param map
	 */
	public static void addPageNum(Map<String, Object> queryMap) {
		if (queryMap.get("page") != null) {
			int rows = Integer.parseInt(queryMap.get("rows").toString());
			int page = Integer.parseInt(queryMap.get("page").toString());
			int pageNum = (page - 1) * rows;
			queryMap.put("pageNum", pageNum);
			queryMap.put("pageRows", rows);
		}
	}

	/**
	 * 生成普通tree的json，
	 * 
	 * @param treeDataList
	 * @param rootIdString
	 * @return
	 */
	public final static List<JsonTreeData> getTreeJson(List<JsonTreeData> treeDataList, String rootIdString,
			String idString) {
		List<JsonTreeData> newTreeDataList = new ArrayList<JsonTreeData>();
		for (JsonTreeData jsonTreeData : treeDataList) {
			if (jsonTreeData.getPid().equals(rootIdString)) {
				if (!idString.equals("")) {
					if (jsonTreeData.getId().equals(idString)) {
						jsonTreeData.setState("open");
						newTreeDataList.add(jsonTreeData);
						jsonTreeData.setChildren(getTreeChildrenNode(jsonTreeData.getId(), treeDataList));
						break;
					}
				} else {
					jsonTreeData.setState("open");
					newTreeDataList.add(jsonTreeData);
					jsonTreeData.setChildren(getTreeChildrenNode(jsonTreeData.getId(), treeDataList));
//					break;
				}

			}
		}
		return newTreeDataList;
	}

	/**
	 * 递归生成json
	 * 
	 * @param pid
	 * @param treeDataList
	 * @return
	 */
	private final static List<JsonTreeData> getTreeChildrenNode(String pid, List<JsonTreeData> treeDataList) {
		List<JsonTreeData> newTreeDataList = new ArrayList<JsonTreeData>();
		for (JsonTreeData jsonTreeData : treeDataList) {
			if (jsonTreeData.getPid() == null)
				continue;
			//
			if (jsonTreeData.getPid().equals(pid)) {
				//
				jsonTreeData.setChildren(getTreeChildrenNode(jsonTreeData.getId(), treeDataList));
				newTreeDataList.add(jsonTreeData);
			}
		}
		return newTreeDataList;
	}

	/**
	 * 生成treegrid的json，参数为List<T>
	 * 
	 * @param tList         为提高效率，list必须按照父级id排序
	 * @param treeIdString
	 * @param treePIdString
	 * @param rootIdString
	 * @return
	 */
	public final static <T> String getTreeGridJson(List<T> tList, String treeIdString, String treePIdString,
			String rootIdString) {
		StringBuilder treeJsonBuilder = new StringBuilder();
		String nameString = "";
		String valueString = "";
		Object valueObject = null;
		int flag = 0;// 当为0时，初始化，当为2时，当前节点已经和之前节点不在同一个目录下了，当为1时，当前节点和之前节点在同一目录下
		treeJsonBuilder.append("[");
		for (T t1 : tList) {
			try {
				PropertyDescriptor pd = new PropertyDescriptor(treePIdString, t1.getClass());
				Method getMethod = pd.getReadMethod();//
				valueObject = getMethod.invoke(t1);// ִ
				valueString = valueObject == null ? "" : valueObject.toString();
				// System.out.println("pid:" + valueString);
				if (valueString.equals(rootIdString)) {
					flag = 1;
					treeJsonBuilder.append("{");
					Field[] fields = t1.getClass().getDeclaredFields();
					for (Field field : fields) {
						nameString = field.getName();
						// System.out.println("name:" + nameString);
						pd = new PropertyDescriptor(nameString, t1.getClass());
						getMethod = pd.getReadMethod();//
						valueObject = getMethod.invoke(t1);//
						valueString = valueObject == null ? "" : valueObject.toString();
						// System.out.println("value:" + valueString);
						treeJsonBuilder.append(
								"\"" + nameString + "\":\"" + valueString.replaceAll("\\\\", "\\\\\\\\") + "\"");
						treeJsonBuilder.append(",");
					}
					treeJsonBuilder.append("\"children\":");
					pd = new PropertyDescriptor(treeIdString, t1.getClass());
					getMethod = pd.getReadMethod();//
					valueObject = getMethod.invoke(t1);//
					valueString = valueObject == null ? "" : valueObject.toString();
					// System.out.println("id:" + valueString);
					treeJsonBuilder.append(getTreeGridJson(tList, treeIdString, treePIdString, valueString));
					treeJsonBuilder.append("},");
				} else if (!valueString.equals(rootIdString) && flag == 1) {
					flag = 2;
				}
				if (flag == 2) {
					break;
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IntrospectionException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		String jsonString = treeJsonBuilder.toString();
		if (jsonString.length() > 1) {
			jsonString = jsonString.substring(0, treeJsonBuilder.toString().length() - 1);
		}
		jsonString += "]";
		return jsonString;

	}

	/**
	 * 获取treegrid的json，区别为止获取自己的，不允许获取同级的
	 * 
	 * @param tModel
	 * @param treeIdString
	 * @param treePIdString
	 * @param rootIdString
	 * @return
	 */
	public final static <T> String getOwnTreeGridJson(List<T> tModel, String treeIdString, String treePIdString,
			String rootIdString, String ownIdString) {
		StringBuilder treeJsonBuilder = new StringBuilder();
		String nameString = "";
		String valueStringPid = "";
		Object valueObjectPid = null;
		String valueStringId = "";
		Object valueObjectId = null;
		treeJsonBuilder.append("[");
		for (T t1 : tModel) {
			try {
				// field1.setAccessible(true);
				PropertyDescriptor pd = new PropertyDescriptor(treePIdString, t1.getClass());
				Method getMethod = pd.getReadMethod();//
				valueObjectPid = getMethod.invoke(t1);// ִ
				valueStringPid = valueObjectPid == null ? "" : valueObjectPid.toString();
				// System.out.println("pid:" + valueString);
				pd = new PropertyDescriptor(treeIdString, t1.getClass());
				getMethod = pd.getReadMethod();//
				valueObjectId = getMethod.invoke(t1);//
				valueStringId = valueObjectId == null ? "" : valueObjectId.toString();
				if (valueStringPid.equals(rootIdString) && valueStringId.equals(ownIdString)) {
					treeJsonBuilder.append("{");
					Field[] fields = t1.getClass().getDeclaredFields();
					for (Field field : fields) {
						nameString = field.getName();
						// System.out.println("name:" + nameString);
						pd = new PropertyDescriptor(nameString, t1.getClass());
						getMethod = pd.getReadMethod();//
						valueObjectPid = getMethod.invoke(t1);//
						valueStringPid = valueObjectPid == null ? "" : valueObjectPid.toString();
						// System.out.println("value:" + valueString);
						treeJsonBuilder.append(
								"\"" + nameString + "\":\"" + valueStringPid.replaceAll("\\\\", "\\\\\\\\") + "\"");
						treeJsonBuilder.append(",");
					}
					// if (!isRoot) {
					treeJsonBuilder.append("\"children\":");
					pd = new PropertyDescriptor(treeIdString, t1.getClass());
					getMethod = pd.getReadMethod();//
					valueObjectPid = getMethod.invoke(t1);//
					valueStringPid = valueObjectPid == null ? "" : valueObjectPid.toString();
					// System.out.println("id:" + valueString);
					treeJsonBuilder.append(getTreeGridJson(tModel, treeIdString, treePIdString, valueStringPid));
					// }
					treeJsonBuilder.append("},");
					break;
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IntrospectionException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		String jsonString = treeJsonBuilder.toString();
		if (jsonString.length() > 1) {
			jsonString = jsonString.substring(0, treeJsonBuilder.toString().length() - 1);
		}
		jsonString += "]";
		return jsonString;

	}

	/**
	 * 生成treegrid的json，区别为参数是(List<Map<String, String>>
	 * 
	 * @param maps
	 * @param treeIdString
	 * @param treePIdString
	 * @param rootIdString
	 * @return
	 */
	public final static String getTreeGridJsonMap(List<Map<String, String>> maps, String treeIdString,
			String treePIdString, String rootIdString) {
		StringBuilder treeJsonBuilder = new StringBuilder();
		String nameString = "";
		String valueString = "";
		treeJsonBuilder.append("[");
		for (Map<String, String> map : maps) {
			try {
				valueString = map.get(treePIdString);
				if (valueString.equals(rootIdString)) {
					treeJsonBuilder.append("{");
					for (Map.Entry<String, String> entry : map.entrySet()) {
						nameString = entry.getKey();
						valueString = entry.getValue();
						System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
						treeJsonBuilder.append("\"" + nameString + "\":\"" + valueString + "\"");
						treeJsonBuilder.append(",");
					}
					treeJsonBuilder.append("\"children\":");
					valueString = map.get(treePIdString);
					treeJsonBuilder.append(getTreeGridJsonMap(maps, treeIdString, treePIdString, valueString));
					// }
					treeJsonBuilder.append("},");
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}
		}
		String jsonString = treeJsonBuilder.toString();
		if (jsonString.length() > 1) {
			jsonString = jsonString.substring(0, treeJsonBuilder.toString().length() - 1);
		}
		jsonString += "]";
		return jsonString;

	}

	/**
	 * 利用反射生成下拉框树状json
	 * 
	 * @param t
	 * @param treeIdString
	 * @param treeTextString
	 * @param treePIdString
	 * @param rootIdString
	 * @param selectString
	 * @param hasRoot
	 * @return
	 */
	public final static <T> String getCobTreeJson(List<T> t, String treeIdString, String treeTextString,
			String treePIdString, String rootIdString, String selectString, boolean hasRoot) {
		StringBuilder treeJsonBuilder = new StringBuilder();
		String nameString = "";
		String valueString = "";
		int flag = 0;// 当为0时，初始化，当为2时，当前节点已经和之前节点不在同一个目录下了，当为1时，当前节点和之前节点在同一目录下
		Object valueObject = null;
		treeJsonBuilder.append("[");
		if (hasRoot) {
			treeJsonBuilder.append("{\"id\":\"0\",\"text\":\"root\"},");
		}
		for (T t1 : t) {
			try {
				// field1.setAccessible(true);
				PropertyDescriptor pd = new PropertyDescriptor(treePIdString, t1.getClass());
				Method getMethod = pd.getReadMethod();//
				valueObject = getMethod.invoke(t1);// ִ
				valueString = valueObject == null ? "" : valueObject.toString();
				// System.out.println("pid:" + valueString);
				if (valueString.equals(rootIdString)) {
					flag = 1;
					treeJsonBuilder.append("{");
					pd = new PropertyDescriptor(treeIdString, t1.getClass());
					getMethod = pd.getReadMethod();//
					valueObject = getMethod.invoke(t1);// ִ
					valueString = valueObject == null ? "" : valueObject.toString();
					// System.out.println("value:" + valueString);
					treeJsonBuilder.append("\"id\":\"" + valueString + "\",");
					pd = new PropertyDescriptor(treeTextString, t1.getClass());
					getMethod = pd.getReadMethod();//
					valueObject = getMethod.invoke(t1);// ִ
					nameString = valueObject == null ? "" : valueObject.toString();
					// System.out.println("text:" + nameString);
					treeJsonBuilder.append("\"text\":\"" + nameString + "\",");

					if (valueString.equals(selectString)) {
						treeJsonBuilder.append("\"checked\":\"true\",");
					}

					treeJsonBuilder.append("\"children\":");
					treeJsonBuilder.append(getCobTreeJson(t, treeIdString, treeTextString, treePIdString, valueString,
							selectString, false));
					treeJsonBuilder.append("},");
				} else if (!valueString.equals(rootIdString) && flag == 1) {
					flag = 2;
				}
				if (flag == 2) {
					break;
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IntrospectionException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		String jsonString = treeJsonBuilder.toString();
		if (jsonString.length() > 1) {
			jsonString = jsonString.substring(0, treeJsonBuilder.toString().length() - 1);
		}
		jsonString += "]";
		return jsonString;

	}

	/**
	 * 根据map生成下拉框树状json
	 * 
	 * @param maps
	 * @param treeIdString
	 * @param treeTextString
	 * @param treePIdString
	 * @param rootIdString
	 * @param selectString
	 * @param hasRoot
	 * @return
	 */
	public final static String getCobTreeJsonMap(List<Map<String, String>> maps, String treeIdString,
			String treeTextString, String treePIdString, String rootIdString, String selectString, boolean hasRoot) {
		StringBuilder treeJsonBuilder = new StringBuilder();
		String nameString = "";
		String valueString = "";
		treeJsonBuilder.append("[");
		if (hasRoot) {
			treeJsonBuilder.append("{\"id\":\"0\",\"text\":\"root\"},");
		}
		for (Map<String, String> map : maps) {
			try {
				valueString = map.get(treePIdString);
				if (valueString.equals(rootIdString)) {
					treeJsonBuilder.append("{");
					valueString = map.get(treeIdString);
					treeJsonBuilder.append("\"id\":\"" + valueString + "\",");
					nameString = map.get(treeTextString);
					treeJsonBuilder.append("\"text\":\"" + nameString + "\",");
					if (valueString.equals(selectString)) {
						treeJsonBuilder.append("\"checked\":\"true\",");
					}
					treeJsonBuilder.append("\"children\":");
					treeJsonBuilder.append(getCobTreeJsonMap(maps, treeIdString, treeTextString, treePIdString,
							valueString, selectString, false));
					treeJsonBuilder.append("},");
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}
		}
		String jsonString = treeJsonBuilder.toString();
		if (jsonString.length() > 1) {
			jsonString = jsonString.substring(0, treeJsonBuilder.toString().length() - 1);
		}
		jsonString += "]";
		return jsonString;

	}

	/**
	 * 根据T反射生成树状下拉框json
	 * 
	 * @param t
	 * @param treeIdString
	 * @param treeTextString
	 * @param treePIdString
	 * @param rootIdString
	 * @param selectString
	 * @param hasRoot
	 * @return
	 */
	public final static <T> String getCobJson(List<T> t, String treeIdString, String treeTextString,
			String treePIdString, String rootIdString, String selectString, boolean hasRoot) {
		StringBuilder treeJsonBuilder = new StringBuilder();
		String nameString = "";
		String valueString = "";
		Object valueObject = null;
		treeJsonBuilder.append("[");
		if (hasRoot) {
			treeJsonBuilder.append("{\"id\":\"0\",\"text\":\"root\"},");
		}
		for (T t1 : t) {
			try {
				// field1.setAccessible(true);
				PropertyDescriptor pd = new PropertyDescriptor(treePIdString, t1.getClass());
				Method getMethod = pd.getReadMethod();//
				valueObject = getMethod.invoke(t1);// ִ
				valueString = valueObject == null ? "" : valueObject.toString();
				// System.out.println("pid:" + valueString);
				if (valueString.equals(rootIdString)) {
					treeJsonBuilder.append("{");
					pd = new PropertyDescriptor(treeIdString, t1.getClass());
					getMethod = pd.getReadMethod();//
					valueObject = getMethod.invoke(t1);//
					valueString = valueObject == null ? "" : valueObject.toString();
					// System.out.println("value:" + valueString);
					treeJsonBuilder.append("\"id\":\"" + valueString + "\",");
					pd = new PropertyDescriptor(treeTextString, t1.getClass());
					getMethod = pd.getReadMethod();//
					valueObject = getMethod.invoke(t1);// ִ
					nameString = valueObject == null ? "" : valueObject.toString();
					// System.out.println("text:" + nameString);
					treeJsonBuilder.append("\"text\":\"" + nameString + "\",");

					if (valueString.equals(selectString)) {
						treeJsonBuilder.append("\"checked\":\"true\"");
					}

					treeJsonBuilder.append("},");
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IntrospectionException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		String jsonString = treeJsonBuilder.toString();
		if (jsonString.length() > 1) {
			jsonString = jsonString.substring(0, treeJsonBuilder.toString().length() - 1);
		}
		jsonString += "]";
		return jsonString;

	}

	/**
	 * 根据map生成树状下拉框
	 * 
	 * @param maps
	 * @param treeIdString
	 * @param treeTextString
	 * @param treePIdString
	 * @param rootIdString
	 * @param selectString
	 * @param hasRoot
	 * @return
	 */
	public final static String getCobJsonMap(List<Map<String, String>> maps, String treeIdString, String treeTextString,
			String treePIdString, String rootIdString, String selectString, boolean hasRoot) {
		StringBuilder treeJsonBuilder = new StringBuilder();
		String nameString = "";
		String valueString = "";
		treeJsonBuilder.append("[");
		if (hasRoot) {
			treeJsonBuilder.append("{\"id\":\"0\",\"text\":\"root\"},");
		}
		for (Map<String, String> map : maps) {
			try {
				valueString = map.get(treePIdString);
				if (valueString.equals(rootIdString)) {
					treeJsonBuilder.append("{");
					valueString = map.get(treeIdString);
					treeJsonBuilder.append("\"id\":\"" + valueString + "\",");
					nameString = map.get(treeTextString);
					treeJsonBuilder.append("\"text\":\"" + nameString + "\",");
					if (valueString.equals(selectString)) {
						treeJsonBuilder.append("\"checked\":\"true\"");
					}
					treeJsonBuilder.append("},");
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}
		}
		String jsonString = treeJsonBuilder.toString();
		if (jsonString.length() > 1) {
			jsonString = jsonString.substring(0, treeJsonBuilder.toString().length() - 1);
		}
		jsonString += "]";
		return jsonString;

	}

	/**
	 * 返回分页json
	 * 
	 * @param json
	 * @return
	 */
	public static String getDatagridPageJson(String json, int count) {
		return "{\"total\":\"" + count + "\",\"rows\":" + json + "}";
	}

	public static JSONObject getDatagridPageJson(Object json, int count) {
		JSONObject gridData = new JSONObject();
		gridData.put("rows", json);
		gridData.put("total", count);
		return gridData;
	}
}
